import React from 'react';
import { Card, Radio, Space } from 'antd';
import { Pie } from '@ant-design/charts';
import type { RadioChangeEvent } from 'antd';
import type { CategoryStat, TagStat } from '@/api/dashboard';

interface DistributionChartProps {
  categories: CategoryStat[];
  tags: TagStat[];
}

interface ChartDataItem {
  type: string;
  value: number;
}

const DistributionChart: React.FC<DistributionChartProps> = ({
  categories,
  tags,
}) => {
  const [chartType, setChartType] = React.useState<'articles' | 'views'>('articles');
  const [dataType, setDataType] = React.useState<'category' | 'tag'>('category');

  const handleMetricChange = (e: RadioChangeEvent) => {
    setChartType(e.target.value);
  };

  const handleDataTypeChange = (e: RadioChangeEvent) => {
    setDataType(e.target.value);
  };

  const data = React.useMemo(() => {
    if (dataType === 'category') {
      return categories.map((item): ChartDataItem => ({
        type: item.categoryName,
        value: chartType === 'articles' ? item.articleCount : item.viewCount,
      }));
    } else {
      return tags.map((item): ChartDataItem => ({
        type: item.tagName,
        value: chartType === 'articles' ? item.articleCount : item.viewCount,
      }));
    }
  }, [categories, tags, dataType, chartType]);

  return (
    <Card
      title="内容分布"
      extra={
        <Space>
          <Radio.Group
            value={dataType}
            onChange={handleDataTypeChange}
            optionType="button"
            buttonStyle="solid"
            size="small"
          >
            <Radio.Button value="category">分类</Radio.Button>
            <Radio.Button value="tag">标签</Radio.Button>
          </Radio.Group>
          <Radio.Group
            value={chartType}
            onChange={handleMetricChange}
            optionType="button"
            buttonStyle="solid"
            size="small"
          >
            <Radio.Button value="articles">文章数</Radio.Button>
            <Radio.Button value="views">访问量</Radio.Button>
          </Radio.Group>
        </Space>
      }
    >
      <Pie
        data={data}
        angleField="value"
        colorField="type"
        radius={0.8}
        label={{
          type: 'outer',
          content: '{name}: {percentage}',
        }}
        interactions={[
          {
            type: 'element-active',
          },
        ]}
        tooltip={{
          formatter: (datum: ChartDataItem) => {
            return {
              name: datum.type,
              value: `${datum.value} ${chartType === 'articles' ? '篇' : '次'}`,
            };
          },
        }}
        animation={{
          appear: {
            animation: 'fade-in',
            duration: 1000,
          },
        }}
      />
    </Card>
  );
};

export default DistributionChart; 